import {observable, action, toJS,runInAction} from 'mobx';
import {locStorage} from '../util/storage';
import http from '../util/axios';
import APIS from '../config/apis';
import {message} from 'antd';


interface LoginValues {
    username: string;
    password: string;
    token: string;
}

interface UserInfoValues {
    username?: string;
    avatar?: string;
    authorized: boolean;
    role: number;
    id: string;
}

class AppStore {

    @observable public loginLoading: boolean = false;

    @observable public userInfo: UserInfoValues = {
        username: '',
        avatar: '',
        role: -1,
        id: '',
        authorized: false
    };
    /**
     * 获取用户信息
     */
    @action public getUserInfo = (): UserInfoValues => {
        const {username, authorized} = this.userInfo;

        if (username && authorized) {
            return this.userInfo as UserInfoValues;
        }

        const info: any = locStorage('chasing_the_wind_info');

        if (info && info.username) {
            // 循环赋值
            for (const key in info) {
                if (info.hasOwnProperty(key)) {
                    this[key] = info.key;
                }
            }

            this.userInfo = info;
            return info as UserInfoValues;
        }

        // 设置为异常状态
        this.userInfo.authorized = false;

        return this.userInfo;
    }

    @action public onLogin = async (values: LoginValues) => {
        try {
            this.loginLoading = true;
            const result = await http.post(APIS.USER_LOGIN, values);

            if (result.code !== 0) {
                runInAction(()=>{
                    this.loginLoading = false;
                    this.userInfo.authorized = false;
                });

                return result.message;
            }

            runInAction(()=>{
                this.userInfo = result.data;
                this.userInfo.authorized = true;
            });

            locStorage('chasing_the_wind_info', toJS(this.userInfo));

            message.success('登录成功');

            return null;

        } catch (err) {
            return err.toString();
        }

    };

    @action public onLogout = async () => {
        try {
            await http.post(APIS.USER_LOGOUT);

            locStorage('chasing_the_wind_info', '');

            message.success('注销成功');

            return true;

        } catch (err) {
            message.error(err.toString());

            return false;
        }
    }
}

export default new AppStore();
